/*------------------- 加载人物 -----------------*/
export default async function initPlayer(user){
  const GLTFLoader = new THREE.GLTFLoader();
  GLTFLoader.load('./source/models/actor.gltf',(gltf) => {
    gltf.scene.name = 'actor'
    gltf.scene.traverse(function (object) {
      if (object.isMesh){
        object.castShadow = true;
        object.receiveShadow = true;
      } 
    });
    mode=gltf

    //挂载动画
    let actor = THREE.SkeletonUtils.clone(gltf.scene);
    const mixer = new THREE.AnimationMixer(actor);
    let walk = mixer.clipAction(gltf.animations[0]);
    let idle = mixer.clipAction(gltf.animations[1]);
    let run = mixer.clipAction(gltf.animations[2]);
    // 当前玩家动画
    action = {
      walking: walk,
      idle: idle,
      run: run
    };
    mixers.push(mixer);

    // 用户id
    player.name = user.name
    player.add(actor);
    player.layers.enableAll();

    player.position.set(...playerPos)
    scene.add(player)
    
    // 用户姓名
    create2DObject( user?.name||user?.nickName||'游客' ,player,user?.pic||user.avatarUrl)
    createCameras()
    getMessage()
  })
}
// 创建二维div
function  create2DObject(name, model,photo) {
  const label = document.createElement("div");
  label.className = "label";
  // label.innerHTML=`
  //   <img class='photo' src=${photo}></img>${name}
  // `
  label.innerHTML=name
  const moonLabel = new Object2DR(label);
  moonLabel.position.set(0, 2, 0);
  model.add(moonLabel);
  moonLabel.layers.set(0);
}
// 添加相机作为玩家的视野
function createCameras() {
  let childNode = new THREE.Object3D();
  let playCamera = childNode.clone();
  playCamera.name = "playerCamera";
  player.add(playCamera);
}

// 建立socket连接接受同步信息
function getMessage(){
  socket.on("message", message => {
    let walking;
    let idle;
    let run;
      if (message.id) {
        let model = scene.getObjectByName(message.id);
        if (model) {
          model.position.set(
            message.playerPosition.x,
            message.playerPosition.y,
            message.playerPosition.z
          );
          if (message.playerQuaternion) {
            model.quaternion.set(
              message.playerQuaternion._x,
              message.playerQuaternion._y,
              message.playerQuaternion._z,
              message.playerQuaternion._w
            );
          }
          if (animations.length > 0) {
            animations.forEach(item => {
              if (item.name == model.name) {
                switch (message.state) {
                  case false:
                    item.action.walking.stop();
                    item.action.idle.play();
                    break;
                  case true:
                    item.action.idle.stop();
                    item.action.walking.play();
                    break;
                }
              }
            });
          }
        } else {
          let model = THREE.SkeletonUtils.clone(mode.scene);
          model.name = message.id;
          let mixer = new THREE.AnimationMixer(model);
          walking = mixer.clipAction(mode.animations[0]);
          idle = mixer.clipAction(mode.animations[1]);
          run = mixer.clipAction(mode.animations[2]);
          let obj = {
            name: message.id,
            action: {
              walking: walking,
              idle: idle,
              run: run
            }
          };
          animations.push(obj);
          scene.add(model);
          create2DObject(message.id, model);
          mixers.push(mixer);
        }
      }
  });
  socket.on("off", data => {
    console.log('user off',data.id)
    if (data.id) {
      let model = scene.getObjectByName(data.id);
      if (model&&model?.traverse) {
        model.traverse(function (obj){
          if(obj.element&&model.children.length>1){
            model.remove(obj)
          }
          if (obj.type === 'Mesh') {
            obj.geometry.dispose();
            obj.material.dispose();
          }
        })
        scene.remove(model);
        if (animations.length > 0) {
          animations.forEach((item,index) => {
            if (item.name == model.name) {
              return animations.splice(index,1)
            }
          });
        }
      } 
    }
  });
}